﻿using IdentityModel;
using IdentityServer4.Models;
using IdentityServer4.Validation;
using JX.Application;
using JX.Infrastructure.Framework;
using Microsoft.AspNetCore.Authentication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace JXIdentityServer
{
	/// <summary>
	/// 自定义验证授权用户信息
	/// </summary>
	public class CustomResourceOwnerValidator : IResourceOwnerPasswordValidator
	{
		private IAdminServiceApp _AdminService;
		private readonly ISystemClock _clock;

		public CustomResourceOwnerValidator(IAdminServiceApp adminService, ISystemClock clock)
		{
			_AdminService = adminService;
			_clock = clock;
		}

		/// <summary>
		/// 验证用户
		/// </summary>
		/// <param name="context"></param>
		/// <returns></returns>
		public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
		{
			if (string.IsNullOrEmpty(context.UserName) || string.IsNullOrEmpty(context.Password))
			{
				context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "无效的秘钥");
			}
			else
			{
				var identityResult = await _AdminService.Login(context.UserName, context.Password);
				if (!identityResult.IsSuccess)
				{
					context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, identityResult.ErrorString);
				}
				else
				{
					context.Result = new GrantValidationResult(
						subject: identityResult.User.FindFirst(ClaimTypes.Sid).Value,
						authenticationMethod: OidcConstants.AuthenticationMethods.Password,
						authTime:_clock.UtcNow.UtcDateTime,
						claims: new Claim[] {
							new Claim(JwtClaimTypes.Id,identityResult.User.FindFirst(ClaimTypes.Sid).Value)
							,new Claim(JwtClaimTypes.Name,identityResult.User.FindFirst(ClaimTypes.Name).Value)
							,new Claim(JwtClaimTypes.Role,identityResult.User.FindFirst(ClaimTypes.Role).Value)
						}
					);
				}
			}
			return;
		}
	}
}
